#!/bin/bash
show_usage="args: [-u, -t, -i ,-c , -s , -p]"

# 环境
username=''
tag=''
imageName=''
containerName=''
serverIp=''
serverPort=''

while getopts ":u:t:i:c:s:p:" opt
do
    case $opt in
        u)
        username=$OPTARG
        ;;
        t)
        tag=$OPTARG
        ;;
        i)
        imageName=$OPTARG
        ;;
        c)
        containerName=$OPTARG
        ;;
        s)
        serverIp=$OPTARG
        ;;
        p)
        serverPort=$OPTARG
        ;;
        ?)
        echo "未知参数 $show_usage"
        exit 1;;
    esac
done

# 远程执行批量脚本
echo ${username}
echo ${serverIp}
ssh -Tq ${username}@${serverIp} << remotessh
#----------------------------------------------
docker pull kcr.kmcloud.kingmed.idc/crm_dev/${imageName}:${tag}

# 查看进程是否存在
now=`date +"%Y-%m-%d %H:%M:%S"`
exist=`docker inspect --format '{{.State.Running}}' ${containerName}`
if [ "${exist}" == "true" ]; then
    docker stop ${containerName}
    echo "${now} stop 容器，容器名称：${containerName}"
fi

# 查看容器是否存在
docker inspect ${containerName} -f '{{.Name}}' > /dev/null
if [ $? -eq 0 ] ;then
    docker rm ${containerName} --force
    echo "docker ${containerName} exist"
else
    echo "docker ${containerName} don't exist"
fi

docker run --network=host --name ${containerName} -d -p ${serverIp}:${serverPort}:${serverPort}/tcp -v /home/jinyu/crm/logs:/home/crm/logs kcr.kmcloud.kingmed.idc/crm_dev/${imageName}:${tag}
exit
#----------------------------------------------
remotessh
echo "======>finish"
